/***************************************************************************
 * 文件名：FMRegistrationProcedure
 * 功能：
 * 说明： 注册程序界面
 * -------------------------------------------------------------------------
 * 创建时间：2025/7/19 14:52:10
 * 创建人：葛浩
 * 邮箱：2094733071@qq.com
 * =========================================================================
 *
 * 修改人：   
 * 修改时间：   
 * 修改说明：   
 ***************************************************************************/
using DevExpress.UIAutomation;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

using Util;

namespace AuxiliaryTools
{
	public partial class FMRegistrationProcedure : XtraForm
	{

		#region Propertys

		/// <summary>
		/// 已注册程序名称列表
		/// </summary>
		private List<string> _functionNameList = new List<string>();

		/// <summary>
		/// 工具配置文件路径
		/// </summary>
		private string _configurationFilePath;

		private int _selectTabIndex = 0;

		/// <summary>
		/// 是否显示运行模式
		/// </summary>
		private bool _isShowStartMode = false;

		/// <summary>
		/// 多工具绑定使用
		/// </summary>
		private List<ProgramConfig> ProgramConfigs = new List<ProgramConfig>();

		#endregion

		#region Const 

		/// <summary>
		/// 按钮图片文件夹名称
		/// </summary>
		private const string c_Image = "Image";

		#endregion

		#region Methods

		/// <summary>
		/// 选择图片路径
		/// </summary>
		/// <returns></returns>
		private string GetImagePath()
		{
			try
			{
				var dialog = new OpenFileDialog();

				dialog.Title = "选择图片文件";
				dialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp;*.gif";
				dialog.Multiselect = false;
				dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);

				if (dialog.ShowDialog() != DialogResult.OK)
				{
					return string.Empty;
				}

				return dialog.FileName;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return string.Empty;
			}
		}

		/// <summary>
		/// 检查参数是否有效
		/// </summary>
		/// <param name="toolName"></param>
		/// <param name="imagePath"></param>
		/// <param name="programEntrance"></param>
		/// <param name="isCheckProgramEntrance"></param>
		/// <returns></returns>
		private string CheckIsValidation(string toolName, string imagePath = "",string programID = "" , string programEntrance = "", bool isCheckProgramEntrance = false)
		{
			string message = string.Empty;

			if (string.IsNullOrEmpty(toolName))
			{
				message += string.Format("{0}工具名称不能为空！", programID);
			}
			else
			{
				if (_functionNameList?.Count > 0 && _functionNameList.Any(p => p.Equals(toolName)))
				{
					message += (!string.IsNullOrEmpty(message) ? ";" : "") + string.Format("{0}工具名称已经被注册，请重新输入！", toolName);
				}
			}

			if (!string.IsNullOrEmpty(imagePath))
			{
				if (!File.Exists(imagePath))
				{
					message += (!string.IsNullOrEmpty(message) ? ";" : "") + "图片文件不存在！";
				}
				else
				{
					if (!FileHelperUtil.IsImageType(imagePath))
					{
						message += (!string.IsNullOrEmpty(message) ? ";" : "") + string.Format("{0}不是图片文件！", imagePath);
					}
				}
			}

			if(isCheckProgramEntrance && string.IsNullOrEmpty(programEntrance))
			{
				message += (string.IsNullOrEmpty(message) ? ";" : "" )+ string.Format("{0}程序入口配置不能为空！", programID);
			}

			return message;
		}

		#endregion

		#region MainFormEvent

		public FMRegistrationProcedure(List<string> functionNameList, string configurationFilePath, int selectTabIndex, bool isVisable = false)
		{
			InitializeComponent();
			_functionNameList = functionNameList;
			_configurationFilePath = configurationFilePath;
			_selectTabIndex = selectTabIndex;
		}

		/// <summary>
		/// Load事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void FMRegistrationProcedure_Load(object sender, EventArgs e)
		{
			radioGroup1.SelectedIndex = _selectTabIndex;
			labStartMode.Visible = _isShowStartMode;
			radioGroup1.Visible = _isShowStartMode;
		}

		/// <summary>
		/// 刷新界面显示数据
		/// </summary>
		private void RefreshData()
		{
			bsData.DataSource = ProgramConfigs;
			grid.MainView.RefreshData();
		}

		/// <summary>
		/// 选择文件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnSelectPath_Click(object sender, EventArgs e)
		{
			try
			{
				var dialog = new OpenFileDialog();
				dialog.Multiselect = false;

				dialog.Filter = "程序文件|*.dll;*.exe";

				if (dialog.ShowDialog() != DialogResult.OK)
				{
					return;
				}

				txtImagePath.TextChanged -= txtImagePath_TextChanged;

				txtToolFilePath.Text = dialog.FileName;

				txtImagePath.TextChanged += txtImagePath_TextChanged;

				string fileName = FileHelperUtil.GetFileName(dialog.FileName);

				txtFileDiretory.Text = fileName;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 确认
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnConfirm_Click(object sender, EventArgs e)
		{
			try
			{
				//错误提示列表
				List<string> messages = new List<string>();

				//程序注册列表
				List<ToolModel> tools = new List<ToolModel>();

				string filePath = txtToolFilePath.Text;
				if (string.IsNullOrEmpty(filePath))
				{
					MessageBox.Show("文件路径不能为空!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return;
				}

				string fileDir = txtFileDiretory.Text;
				if (string.IsNullOrEmpty(fileDir))
				{
					MessageBox.Show("注册到程序框架中的目录不能为空!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return;
				}

				#region 应用

				string toolName = txtToolName.Text;
				string imagePath = txtImagePath.Text;

				if (_selectTabIndex == 1)
				{
					string message = CheckIsValidation(toolName, imagePath);
					if (!string.IsNullOrEmpty(message))
					{
						messages.Add(message);
					}
					else
					{
						tools.Add(new ToolModel()
						{
							Name = toolName,
							ToolFileDir = fileDir,
							ProgramEntrance = Path.GetFileName(filePath),
							ImagePath = imagePath,
							StartMode = ProgramStartMode.IndependentThreads,
							IsFixed = ckbIsFixed.Checked,
						});
					}
				}

				#endregion

				#region 多个程序注册检测

				if (_selectTabIndex == 0)
				{
					if (ProgramConfigs?.Count == 0)
					{
						MessageBox.Show("请添加工具配置信息!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
						return;
					}

					foreach(var config in ProgramConfigs)
					{
						string message = CheckIsValidation(config.FunctionName, config.ImagePath, config.ID, config.ProgramEntrance, true);
						if (!string.IsNullOrEmpty(message))
						{
							messages.Add(message);
							continue;
						}

						tools.Add(new ToolModel()
						{
							Name = config.FunctionName,
							ToolFileDir = fileDir,
							ProgramEntrance = string.Format("{0};{1}", Path.GetFileName(filePath), config.ProgramEntrance),
							ImagePath = config.ImagePath,
							StartMode = ProgramStartMode.InterfaceCall,
							IsFixed = config.IsFixed,
						});
					}
				}

				#endregion

				#region 判断参数是否合法

				if (messages?.Count > 0)
				{
					string message = string.Empty;
					for (int i = 0; i < messages.Count; i++)
					{
						message += string.Format("{0}:", i + 1) + messages[i] + (i <= messages.Count - 1 ? "\r\n" : "");
					}

					MessageBox.Show(message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return;
				}

				#endregion

				#region 拷贝文件至主程序目录下

				if (tools?.Count == 0)
				{
					return;
				}

				//构建目标文件夹
				string targetDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,fileDir);
				if (!Directory.Exists(targetDir))
				{
					Directory.CreateDirectory(targetDir);
				}

				//拷贝文件
				//构建图片目录
				FileHelperUtil.CopyFolder(Path.GetDirectoryName(filePath), targetDir);

				#endregion

				#region 向工具配置文件中新增

				string targetImageDir = Path.Combine(targetDir, c_Image);
				if(tools.Any(p=>p.ImagePath != string.Empty) && !Directory.Exists(targetImageDir))
				{
					Directory.CreateDirectory(targetImageDir);
				}

				foreach(var tool in tools)
				{
					if(tool == null) {  continue; }

					if (!string.IsNullOrEmpty(tool.ImagePath))
					{
						string imageName = Path.GetFileName(tool.ImagePath);
						//拷贝图片到指定目录下
						File.Copy(tool.ImagePath, Path.Combine(targetImageDir, imageName), true);
						tool.ImagePath = imageName;
					}
				}

				//添加工具配置文件
				if(AuxiliaryToolUtil.AddToolConfigurations(_configurationFilePath, tools))
				{
					MessageBox.Show("注册成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					DialogResult = DialogResult.OK;
				}
				else
				{
					MessageBox.Show("注册失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
				}

				#endregion
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 关闭
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnClose_Click(object sender, EventArgs e)
		{
			DialogResult = DialogResult.Cancel;
		}

		#endregion

		#region MulitiFunctionTanEvent

		/// <summary>
		/// 新增
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnAddRow_Click(object sender, EventArgs e)
		{
			try
			{
				ProgramConfigs.Add(new ProgramConfig()
				{
					ID = System.DateTime.Now.ToString("yyyyMMddHHmmss"),
					IsFixed = true,
				});

				RefreshData();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 移除
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnDelete_Click(object sender, EventArgs e)
		{
			try
			{
				var gridView = grid.MainView as GridView;
				if (gridView == null)
				{
					return;
				}

				var data = gridView.GetFocusedRow() as ProgramConfig;
				if(data == null)
				{
					MessageBox.Show("请选择数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				//移除数据
				ProgramConfigs.Remove(data);

				RefreshData();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 选择图片
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnSelectImage_Click(object sender, EventArgs e)
		{
			try
			{
				var gridView = grid.MainView as GridView;
				if (gridView == null)
				{
					return;
				}

				var data = gridView.GetFocusedRow() as ProgramConfig;
				if (data == null)
				{
					MessageBox.Show("请选择数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				data.ImagePath = GetImagePath();

				RefreshData();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#endregion

		#region OtherEvent

		/// <summary>
		/// 单个程序注册选择图片
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnSelectPicture_Click(object sender, EventArgs e)
		{
			try
			{
				string imagePath = GetImagePath();

				txtImagePath.TextChanged -= txtImagePath_TextChanged;

				txtImagePath.Text = imagePath;

				txtImagePath.TextChanged += txtImagePath_TextChanged;

				if (!File.Exists(imagePath))
				{
					return;
				}

				pictureEdit1.Image = Image.FromFile(imagePath);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 图片路径改变事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void txtImagePath_TextChanged(object sender, EventArgs e)
		{
			if (!File.Exists(txtImagePath.Text))
			{
				pictureEdit1.Image = null;
				return;
			}

			pictureEdit1.Image = Image.FromFile(txtImagePath.Text);
		}

		/// <summary>
		/// 工具文件Text改变事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void txtToolFilePath_TextChanged(object sender, EventArgs e)
		{
			if (!File.Exists(txtToolFilePath.Text))
			{
				txtFileDiretory.Text = string.Empty;
				return;
			}

			txtFileDiretory.Text = FileHelperUtil.GetFileName(txtToolFilePath.Text);
		}

		/// <summary>
		/// 切换运行模式
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void radioGroup1_SelectedIndexChanged(object sender, EventArgs e)
		{
			xtraTabControl1.SelectedTabPageIndex = radioGroup1.SelectedIndex;
			_selectTabIndex = radioGroup1.SelectedIndex;
		}

		#endregion
	}
}
